package st1.apiT1.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import st1.apiT1.dto.AddRequest;
import st1.apiT1.dto.AddResponse;

@RestController
public class ComputeController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }
    
    @RequestMapping(value = "/addByDto" ,method = RequestMethod.POST)
    public AddResponse addByDto(@RequestBody AddRequest req) {
    	try{ 
            ServiceInstance instance = client.getLocalServiceInstance();
            Integer r = req.getA() + req.getB();
            logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
            AddResponse res=new AddResponse();
            res.setCode("000000");
            res.setMsg(req.getName());
            res.setResult(r);
            return res;
    	}catch(Exception ex)
    	{
    		logger.error(ex.getMessage(), ex);
    		AddResponse res=new AddResponse();
            res.setCode("500000");
            res.setMsg(ex.getMessage()); 
            return res;
    	}
    }

}